/*
 * @(#)ActionUtil.java 0.5 08/12/04
 *
 * Copyright 2008 100town.com. All rights reserved.
 * Use is subject to license terms.
 */

package org.collada.util.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;

import org.collada.model.Action;
import org.collada.model.ControlKey;
import org.collada.model.ModifierKey;

public class ActionUtil {
	public static int modifierKey(ModifierKey modifierKey){
		switch (modifierKey){
		case CTRL_DOWN_MASK:
			return InputEvent.CTRL_DOWN_MASK;
		case ALT_DOWN_MASK:
			return InputEvent.ALT_DOWN_MASK;
		case SHIFT_DOWN_MASK:
			return InputEvent.SHIFT_DOWN_MASK;
		default:
			return -1;			
		}
	}
	public static KeyListener toKeyListener(final Action action){
		ControlKey controlKey = action.getControlKey();
		if(controlKey!=null && controlKey.getKey()>0){
			final int actionKey = controlKey.getKey();
			List<ModifierKey> modifierKeys = controlKey.getModifierKeys();
			int modifierMask1 = 0;
			int modifierMask2 = 0;
			int modifierMask3 = 0;
			if(modifierKeys!=null && modifierKeys.size()>0){
				modifierMask1 = modifierKey(modifierKeys.get(0));
				if(modifierKeys.size()>1){
					modifierMask2 = modifierKey(modifierKeys.get(1));
				}
				if(modifierKeys.size()>2){
					modifierMask3 = modifierKey(modifierKeys.get(2));
				}
			}
			final int onmask = modifierMask1 | modifierMask2 | modifierMask3;
			final int offmask = InputEvent.CTRL_DOWN_MASK |
				InputEvent.SHIFT_DOWN_MASK  |
				InputEvent.ALT_DOWN_MASK & onmask;
			KeyAdapter ka = new KeyAdapter(){
				public void keyPressed(KeyEvent e){
					if(e.getKeyCode()==actionKey){
						if(((e.getModifiersEx() & (onmask | offmask)) == onmask)){
							if(action.getActionListeners()!=null && action.getActionListeners().size()>0){
								for(Object object: action.getActionListeners()){
									if(object instanceof ActionListener){
										ModelEvent actionEvent = new ModelEvent(action, e.getSource(),
									              ActionEvent.ACTION_PERFORMED, action.getActionID());
										((ActionListener)object).actionPerformed(actionEvent);
									}else{
										System.out.println("ccc");
									}
								}
							}else{
								System.out.println("sddd");
							}
						}
					}
				}
				public void keyReleased(KeyEvent e){
				}
				public void keyTyped(KeyEvent e){}
			};
			return ka;	
		}
		return null;
	}
}